#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = []

from uuid import uuid4

from com.mousechsh.business.lib.MouseChshAuthorizationAnnotition import MouseChshRemoteAuthorizationAnnotition
from com.mousechsh.business.lib.model.MouseChshKeyValueModel import MouseChshKeyValueModel
from com.mousechsh.business.lib.model.MouseChshModuleModel import MouseChshModuleModel
from com.mousechsh.business.lib.model.MouseChshPermissionModel import MouseChshPermissionModel
from com.mousechsh.business.lib.model.MouseChshUserModel import MouseChshUserModel
from com.mousechsh.common.data.MouseChshDao import MouseChshDao
from com.mousechsh.common.data.MouseChshData import mousechsh_data_merge
from com.mousechsh.common.io.db.MouseChshPostgresql import MouseChshPostgresql
from com.mousechsh.common.middle.http.MouseChshHttpHeader import mousechsh_http_header_accept_language_annotation
from com.mousechsh.common.middle.rest_api.MouseChshRestApi import mousechsh_rest_api_annotation
from com.mousechsh.common.middle.router.MouseChshCorsAnnotition import mousechsh_cors_annotation
from com.mousechsh.common.middle.router.MouseChshHttpRouter import mousechsh_http_router_annotation
from com.mousechsh.common.util.MouseChshDateTime import MouseChshDateTime


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/permission/add')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _addPermission(params):
	lang = params.get('lang', 'zh-cn')
	permission = MouseChshPermissionModel()
	permission.set_data(params)
	permission.Id = str(uuid4()).upper()
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   INSERT INTO "A_Application"."T_Permission"(
		   "C_Id",
		   "C_CrOn",
		   "C_MoOn",
		   "L_Scheme",
		   "X_Data",
		   "L_Module_Id",
		   "L_TargetType",
		   "L_Common_Id",
		   "C_Inherit",
		   "C_Content"
	   ) VALUES (
		   %(id)s,
		   %(cron)s,
		   %(moon)s,
		   'Permission',
		   '{}',
		   %(module)s,
		   %(target)s,
		   %(common)s,
		   %(inherit)s,
		   %(content)s
	   )
		   ''', {
			'id': permission.get('Id'),
			'cron': MouseChshDateTime().to_timestamp(),
			'moon': MouseChshDateTime().to_timestamp(),
			'module': permission.get('Module'),
			'target': permission.get('Target'),
			'common': permission.get('CommonId'),
			'inherit': (False if permission.get('Inherit') == 0 else True),
			'content': permission.get('Content')
		}
	)
	db.commit()
	db.close()
	return permission.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/permission/remove')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _removePermission(params):
	module = MouseChshPermissionModel()
	module.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   DELETE FROM "A_Application"."T_Permission"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'id': module.get('Id')
		}
	)
	db.commit()
	db.close()
	return True


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/permission/update')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _updatePermission(params):
	lang = params.get('lang', 'zh-cn')
	permission = MouseChshPermissionModel()
	permission.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   "C_Id",
		   "C_CrOn",
		   "C_CrBy",
		   "C_MoOn",
		   "C_MoBy",
		   "C_RvOn",
		   "C_RvBy",
		   "C_St",
		   "C_Owner",
		   "C_Flag",
		   "L_Scheme",
		   "X_Data",
		   "X_Property",
		   "L_Module_Id" AS "C_Module_Id",
		   "L_TargetType" AS "C_TargetType",
		   "L_Common_Id" AS "C_Common_Id",
		   "C_Inherit",
		   "C_Content"
	   FROM "A_Application"."T_Permission"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'lang': lang,
			'id': permission.get('Id')
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshPermissionModel)
	permissions = dao.parse(data)
	if len(permissions) <= 0:
		return
	permission = mousechsh_data_merge(permissions[0], permission)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   UPDATE "A_Application"."T_Permission" SET
		   "C_MoOn"      = %(moon)s,
		   "L_Scheme"    = 'Permission',
		   "X_Data"      = '{}',
		   "L_Module_Id" = %(module)s,
		   "L_TargetType" = %(target)s,
		   "L_Common_Id" = %(common)s,
		   "C_Inherit"   = %(inherit)s,
		   "C_Content"   = %(content)s
	   WHERE "C_Id"      = %(id)s
		   ''', {
			'moon': MouseChshDateTime().to_timestamp(),
			'module': permission.get('Module'),
			'target': permission.get('Target'),
			'common': permission.get('CommonId'),
			'inherit': (False if permission.get('Inherit') == 0 else True),
			'content': permission.get('Content'),
			'id': permission.get('Id')
		}
	)
	db.commit()
	db.close()
	return permission.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/permission/get')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _getPermission(params):
	lang = params.get('lang', 'zh-cn')
	permission = MouseChshPermissionModel()
	permission.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   A."C_Id",
		   A."C_CrOn",
		   A."C_CrBy",
		   A."C_MoOn",
		   A."C_MoBy",
		   A."C_RvOn",
		   A."C_RvBy",
		   A."C_St",
		   A."C_Owner",
		   A."C_Flag",
		   A."L_Scheme",
		   A."X_Data",
		   A."X_Property",
		   A."L_Module_Id" AS "C_Module_Id",
		   A."L_TargetType" AS "C_PermissionTarget",
		   A."L_TargetType" AS "L_PermissionTarget_Key",
		   COALESCE( C."X_Display" ->> %(lang)s, C."X_Display" ->> ( C."X_Display" ->> '' ) ) AS "L_PermissionTarget_Display",
		   A."L_Common_Id" AS "C_CommonId",
		   A."L_Common_Id" AS "L_CommonId_Id",
		   COALESCE( D."X_Display" ->> %(lang)s, D."X_Display" ->> ( D."X_Display" ->> '' ) ) AS "L_CommonId_Display",
		   A."C_Inherit",
		   A."C_Content"
	   FROM "A_Application"."T_Permission" A
	   INNER JOIN "A_Application"."T_Module" B
		   ON A."L_Module_Id" = B."C_Id"
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" C
		   ON A."L_TargetType" = C."C_Key"
	   LEFT OUTER JOIN "A_AD"."T_User" D
		   ON A."L_Common_Id" = D."C_Id"
	   WHERE A."L_Module_Id"  = %(module)s
	   ORDER BY A."C_Order" ASC
	   LIMIT 100
		   ''', {
			'lang': lang,
			'module': permission.get('Module')
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshPermissionModel)
	dao.set_extra_model(MouseChshModuleModel)
	dao.set_extra_model(MouseChshUserModel, key='CommonId')
	dao.set_extra_model(MouseChshKeyValueModel, key='PermissionTarget')
	permissions = dao.parse(data)
	return permissions
